package com.archgeek.calcite;

import org.apache.calcite.adapter.csv.CsvSchema;
import org.apache.calcite.adapter.csv.CsvTable;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.tools.FrameworkConfig;
import org.apache.calcite.tools.Frameworks;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.tools.RelRunners;

import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

/**
 * @author pizhihui
 * @date 2024-05-30 13:23
 */
public class C2_RelNodeQuery {


    public static void main(String[] args) throws SQLException {

        /**
         * ================ 构建 schema
         */
        SchemaPlus schema = Frameworks.createRootSchema(true);
        File file = new File(C2_RelNodeQuery.class.getClassLoader().getResource("").getPath());

        CsvSchema csvSchema = new CsvSchema(file, CsvTable.Flavor.SCANNABLE);
        schema.add("orders", csvSchema.getTable("orders"));
        schema.add("consumers", csvSchema.getTable("consumers"));

        System.out.println(schema.getTableNames());

        FrameworkConfig config =
                Frameworks.newConfigBuilder()
                        .defaultSchema(schema)
                        .build();

        /**
         * 重要的代码
         */
        RelBuilder relBuilder = RelBuilder.create(config);
        RelNode relNode = relBuilder
                .scan("consumers")   // select * from consumers
                .project(                        // select firstname,lastname from consumers
                        relBuilder.field("firstname"),
                        relBuilder.field("lastname")
                )
                .build();


        System.out.println(RelOptUtil.toString(relNode));


        System.out.println("==============[result]");

        PreparedStatement run = RelRunners.run(relNode);
        ResultSet resultSet = run.executeQuery();

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            System.out.print(metaData.getColumnName(i) + "\t");
        }
        System.out.println();

        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                System.out.print(resultSet.getString(i) + "\t");
            }
            System.out.println();
        }

    }

}
